package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"merchant/merchantmanagerrpc/internal/svc"
	"merchant/merchantmanagerrpc/merchantmanagerrpc"
	"merchant/models/mysql"
	"merchant/models/redisinit"
	"time"
)

type MerchantListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMerchantListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MerchantListLogic {
	return &MerchantListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *MerchantListLogic) MerchantList(in *merchantmanagerrpc.MerchantListRequest) (*merchantmanagerrpc.MerchantListResponse, error) {
	// todo: add your logic here and delete this line

	var merchant []mysql.Merchant

	mysql.DB.Debug().Find(&merchant)

	get := redisinit.Client.Get("merchantlist")
	if get.Val() == "" {
		mysql.DB.Debug().Find(&merchant)
		marshal, _ := json.Marshal(&merchant)
		redisinit.Client.Set("merchantlist", marshal, time.Second*60)
		fmt.Println("mysql")
	} else {
		json.Unmarshal([]byte(get.Val()), &merchant)
		fmt.Println("redis")
	}

	var lists []*merchantmanagerrpc.MerchantList

	for _, m := range merchant {
		list := merchantmanagerrpc.MerchantList{
			Name:  m.Name,
			Cate:  m.Cate,
			Timed: m.Timed,
			Id:    int64(m.ID),
		}
		lists = append(lists, &list)
	}

	return &merchantmanagerrpc.MerchantListResponse{
		List: lists,
	}, nil
}
